package com.googlecode.publicholiday.repository.jdbc;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

public class H2JdbcBootstrapper implements Bootstrapper {

    private final static String CHECK_BOOTSTRAP_SQL = "SELECT country_code FROM public_holiday WHERE 1=2";
    public static final String CREATE_PUBLIC_HOLIDAY_TABLE_SQL = "" +
            "CREATE TABLE public_holiday " +
            "( country_code VARCHAR(3) NOT NULL " +
            ", holiday_date DATE NOT NULL " +
            ", CONSTRAINT public_holiday_pk PRIMARY KEY ( country_code, holiday_date ) )";

    private final DataSource dataSource;

    public H2JdbcBootstrapper(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    @Override
    public boolean isBootstrappingRequired() {
        try {
            getStatement().executeQuery(CHECK_BOOTSTRAP_SQL);
        } catch (SQLException ignore) {
            return true;
        }
        return false;
    }

    @Override
    public void execute() {
        if (isBootstrappingRequired()) {
            try {
                getStatement().execute(CREATE_PUBLIC_HOLIDAY_TABLE_SQL);
            } catch (SQLException e) {
                throw new RuntimeException("Bootstrapping Failed", e);
            }
        }
    }

    private Statement getStatement() {
        Connection connection = null;
        try {
            connection = dataSource.getConnection();
            return connection.createStatement();
        } catch (SQLException e) {
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException ignore) {
                }
            }
            throw new RuntimeException("Could not obtain a connection to the database", e);
        }
    }
}
